package com.runen.infinitemovement.tool;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.rxnetlibrary.utils.AppUtils;
import com.runen.rxnetlibrary.utils.FileUtils;
import com.runen.rxnetlibrary.utils.IntentUtils;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * APP版本检查及下载
 *
 * @author Administrator
 */
public class AppDownloadManager {


    private File tempFile = null;
    /**
     * 更新应用版本标记
     */
    private static final int UPDARE_TOKEN = 0x29;

    /**
     * 准备安装新版本应用标记
     */
    private static final int INSTALL_TOKEN = 0x31;

    private Context mContext;

    /**
     * 下载应用的对话框
     */
    private Dialog dialog;

    /**
     * 下载应用的进度条
     */
    private ProgressBar progressBar;

    /**
     * 进度条的当前刻度值
     */
    private int curProgress;

    /**
     * 用户是否取消下载
     */
    private boolean isCancel;


    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDARE_TOKEN:
                    progressBar.setProgress(curProgress);
                    break;
                case INSTALL_TOKEN:
                    installApp();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 显示下载进度对话框
     */
    private void showDownloadDialog(final String url) {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.progress_bar, null);
        progressBar = view.findViewById(R.id.progressBar);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        Builder builder = new Builder(mContext);
        builder.setView(view);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                isCancel = true;
            }
        });
        //请求动态权限
        PermissionUtils.permission(PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        downloadApp(url);
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }

    /**
     * 下载新版本应用
     */
    private void downloadApp(final String getVersionUrl) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url;
                InputStream in = null;
                FileOutputStream out = null;
                HttpURLConnection conn = null;
                try {
                    url = new URL(getVersionUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    long fileLength = conn.getContentLength();
                    in = conn.getInputStream();
                    File dirFile = FileUtils.getSDPath(mContext);
                    // 判断sdcard是否存在,不存在放到手机内置内存中
                    if (null != dirFile) {
                        File rootFile = new File(dirFile, "/"
                                + AppUtils.getAppPackageName());
                        if (!rootFile.exists() && !rootFile.isDirectory()) {
                            rootFile.mkdir();
                        }
                        tempFile = new File(dirFile,
                                "/" + AppUtils.getAppPackageName()
                                        + "app.apk");
                    } else {
                        // 在内存中存储
                        tempFile = new File(Constant.CACHE_ROOT, "app.apk");
                    }
                    if (tempFile.exists()) {
                        tempFile.delete();
                    }
                    LogUtil.e("tempFile", tempFile.getPath());
                    tempFile.createNewFile();
                    out = new FileOutputStream(tempFile);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    long readedLength = 0L;
                    while ((len = in.read(buffer)) != -1) {
                        // 用户点击“取消”按钮，下载中断
                        if (isCancel) {
                            break;
                        }
                        out.write(buffer, 0, len);
                        readedLength += len;
                        curProgress = (int) (((float) readedLength / fileLength) * 100);
                        handler.sendEmptyMessage(UPDARE_TOKEN);
                        if (readedLength >= fileLength) {
                            dialog.dismiss();
                            // 下载完毕，通知安装
                            handler.sendEmptyMessage(INSTALL_TOKEN);
                            break;
                        }
                    }
                    out.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        LogUtil.e("版本跟新", "zou");
        if (!tempFile.exists()) {
            return;
        }
        LogUtil.e("版本跟新", "zou2");
        // 跳转到新版本应用安装页面
        Intent intent = IntentUtils.getInstallAppIntent(tempFile, true);
        mContext.startActivity(intent);
//        openAPKFile((Activity) mContext, tempFile);
    }

    public AppDownloadManager(Context context, String dowloadUrl, String descr) {
        mContext = context;
        showUpdataDialog(dowloadUrl, descr);
    }


    private void showUpdataDialog(final String dowloadUrl, String descr) {
        CommonDialog.getInstance(mContext, "版本更新", descr, "取消", "确定", 1).setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void onSendListener() {


            }

            @Override
            public void onDismiss() {
                showDownloadDialog(dowloadUrl);
            }
        });
    }


    /**
     * 打开安装包
     *
     * @param mContext
     * @param fileUri
     */
    public void openAPKFile(Activity mContext, File fileUri) {
//        DataEmbeddingUtil.dataEmbeddingAPPUpdate(fileUri);
        // 核心是下面几句代码
        if (null != fileUri) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                File apkFile = fileUri;
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".tool.MyFileProvider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
//                            ToastUtil.makeText(MyApplication.getContext(), MyApplication.getContext().getString(R.string.string_install_unknow_apk_note), false);
                            startInstallPermissionSettingActivity();
                            return;
                        }
                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    mContext.startActivity(intent);
                }
            } catch (Throwable e) {
                e.printStackTrace();
//                DataEmbeddingUtil.dataEmbeddingAPPUpdate(e.toString());
//                CommonUtils.makeEventToast(MyApplication.getContext(), MyApplication.getContext().getString(R.string.download_hint), false);
            }
        }
    }


    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    public static String getSDPath(Context context) {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            if (Build.VERSION.SDK_INT >= 29) {
                //Android10之后
                sdDir = context.getExternalFilesDir(null);
            } else {
                sdDir = Environment.getExternalStorageDirectory();// 获取SD卡根目录
            }
        } else {
            sdDir = Environment.getRootDirectory();// 获取跟目录
        }
        return sdDir.toString();
    }

}
